import protobuf from 'protobufjs'

/**
 * @param {Object} 十六进制转为Uint8Array类型
 */
function hexStringToUint8Array(hexString) {
	let uintArray = new Uint8Array(hexString.match(/.{2}/g).map(byte => parseInt(byte, 16)));
	return uintArray;
}

/**
 * 获取反序列后的json
 * @param {Object} hexString 十六进制字符串
 * @param {String} messageType 消息类型
 */
async function getJson(hexString, messageType = 'GetAllDenominationResponse') {
	// demo
	hexString =
		'0a06e98193e695990a06e58492e6959912770a06e98193e69599126d0a06e4b889e6b8850a0fe4ba94e696b9e4ba94e88081e5909b122c0a06e4b889e6b88512220a0f08011201312201312a0531302d31320a0f08021201322201322a0530312d313212240a0fe4ba94e696b9e4ba94e88081e5909b12110a0f08031201332201332a0531312d3035122f0a06e58492e6959912250a06e58492e69599121b0a06e58492e6959912110a0f08041201342201342a0530352d3039'

	//加载proto文件
	let root = await protobuf.load("/proto/worship.proto");

	// 获取消息类型
	var MyMessage = root.lookupType(messageType);

	//转换为Uint8Array消息
	let buffer = hexStringToUint8Array(hexString);
	// console.log('buffer', buffer)

	// 解码protobuf数据
	var message = MyMessage.decode(buffer);

	// 打印解码后的消息对象
	// console.log('message', message);

	// 如果需要，可以进一步将消息转换为JSON对象
	var json = MyMessage.toObject(message, {
		longs: String,
		enums: String,
		bytes: String,
		defaults: true,
		arrays: true,
		objects: true
	});

	return json
}

export default getJson;

console.log(getJson())